<script setup>
import { getGoodsDetailAPI,getProductReviewsAPI } from "@/apis/detail";
import { onMounted, ref } from "vue";
import { onBeforeRouteUpdate, useRoute, useRouter } from "vue-router";
import { Message, WarnTriangleFilled } from "@element-plus/icons-vue";
import { useCarStore } from "@/stores/car";
import { ElMessage } from "element-plus";
import { getProductById } from "@/apis/product";
import { getUserInfoAPI } from "@/apis/user";
import {createConversation} from "@/apis/chat/conversation.js";
import {userInfoStore} from "@/stores/user.js";
import DetailHot from "@/views/Detail/components/DetailHot.vue";

const route = useRoute();
const router = useRouter();

const goodsDetailData = ref({});
const productImages = ref([]);
const reviews = ref([]); // 新增评论数据
const loadingReviews = ref(false); // 加载状态

const getGoodsDetailData = async (id) => {
  console.log("id: getGoodsDetailData ", id);
  if (id) {
    let res = await getProductById(id);
    console.log("res: ", res);
    goodsDetailData.value = res.data.products;
    productImages.value = res.data.productImages.map((item) => item.imageUrl);
    console.log("goodsDetailData.value: ", goodsDetailData.value);
  }
};

// 新增：获取商品评论
const getProductReviews = async (productId) => {
  try {
    loadingReviews.value = true;
    const res = await getProductReviewsAPI(productId);
    // const res = [];
    reviews.value = res.data;
    console.log("商品评论:", reviews.value);
  } catch (error) {
    console.error("获取评论失败:", error);
    ElMessage.error("获取评论失败");
  } finally {
    loadingReviews.value = false;
  }
};

const count = ref(1);
const countChange = () => {};

//加入购物车
const carStore = useCarStore();
const addCar = () => {
  if (goodsDetailData.value.productId) {
     console.log("商品选择的数量",count.value)
    carStore.addCar({
      productId: goodsDetailData.value.productId,
      name: goodsDetailData.value.title,
      picture: productImages.value[0].imageUrl,
      count: count.value,
      price: goodsDetailData.value.price,
      attrsText: goodsDetailData.value.description,
      selected: true,
    });
    // ElMessage.success("添加成功");
  } else {
    ElMessage.warning("请选择商品");
  }
};

const sellerInfo = ref({});
const getSellerInfo = async (id) => {
  const res = await getUserInfoAPI({ userId: id });
  sellerInfo.value = res.data;
  console.log("sellerInfo : ", sellerInfo.value);
};

onMounted(async () => {
  if (route.params.id) {
    await getGoodsDetailData(route.params.id);
    if (goodsDetailData.value.userId) {
      console.log("goodsDetailData.value.userId: ", goodsDetailData.value.userId);
      await getSellerInfo(goodsDetailData.value.userId);
    }
    // 新增：加载评论数据
    await getProductReviews(route.params.id);
    console.log("route.params.id: ", route.params.id);
  }
});

onBeforeRouteUpdate((to) => getGoodsDetailData(to.params.id));

const gotoPay = () => {
  if (goodsDetailData.value.productId) {
    console.log("productImages.value[0].imageUrl: ", productImages.value[0]);
    // 这里可以添加跳转到支付页面的逻辑
    router.push({
      path: "/order",
      query: {
        productId: goodsDetailData.value.productId,
        title: goodsDetailData.value.title,
        description: goodsDetailData.value.description,
        imageUrl: productImages.value[0],
        count: count.value,
        price: goodsDetailData.value.price,
        sellerId: JSON.stringify(sellerInfo.value.userId),
      },
    });
    console.log("跳转到支付页面");
  } else {
    ElMessage.warning("请选择商品");
  }
};

const contactSeller = async (sellerInfo, goodsData) => {
  console.log("sellerInfo: ", userInfoStore().userInfo);
  const resp = await createConversation({
    type: 'PERSONAL',
    participants: [userInfoStore().userInfo.userId, sellerInfo.userId]
  })

  if (resp.code === 200) {
    const fullPath = router.resolve({
      path: '/chat',
      query: {
        conversationId: resp.conversationId,
        productId: goodsData.productId
      }
    }).href;
    window.open(fullPath);
  }

};
</script>

<template>
  <div class="xtx-goods-page">
    <div class="container">
      <div class="bread-container">
      </div>
      <!-- 商品信息 -->

      <div class="info-container">
        <div>
          <div class="goods-info">
            <div class="media">
              <!-- 图片预览区 -->
              <ImagView :imageList="productImages" />

            </div>
            <div class="spec">
              <p class="g-price">
                <span>￥</span>{{ goodsDetailData?.price }}
              </p>
              <!-- 商品信息区 -->
              <p class="g-name">{{ goodsDetailData?.title }}</p>
              <p class="g-desc">{{ goodsDetailData?.description }}</p>

              <div class="g-service">
                <div class="seller-section">
                  <RouterLink :to="`/chartMsg/${sellerInfo.userId}`" class="seller-link">
                    <el-avatar shape="square" size="large" :src="sellerInfo.avatarUrl" />
                    <div class="seller-info">
                      <span class="seller-name">{{ sellerInfo.realName }}</span>
                      <span class="seller-phone">{{ sellerInfo.phone }}</span>
                      <el-button @click.prevent="contactSeller(sellerInfo, goodsDetailData)" type="success" :icon="Message" size="small"
                        >联系卖家</el-button
                      >
                    </div>
                  </RouterLink>
                  <RouterLink
                    :to="`/report/${goodsDetailData.productId}`"
                    class="report-link"
                  >
                    <el-button type="danger" :icon="WarnTriangleFilled" size="small"
                      >举报</el-button
                    >
                  </RouterLink>
                </div>

                <div class="number-box">
                  <el-input-number
                    v-model="count"
                    :max="goodsDetailData?.stock"
                    :min="1"
                    @change="countChange"
                    size="small"
                  />
                  <p v-if="count > goodsDetailData?.stock" class="error-message">
                    库存不足
                  </p>
                  <p v-else-if="count < 1" class="error-message">数量不能小于1</p>
                  <p
                    v-else-if="count === goodsDetailData?.stock"
                    class="success-message"
                  >
                    库存充足
                  </p>
                  <p v-else class="info-message">可以购买</p>
                </div>

                <div class="btn-group">
                  <el-button size="large" type="primary" class="btn" @click="gotoPay">
                    立即购买
                  </el-button>
                  <el-button size="large" class="btn" @click="addCar">
                    加入购物车
                  </el-button>
                </div>
              </div>
              <!-- sku组件 -->
              <!-- <Sku :goods="goodsDetailData" @change="skuChange" /> -->
              <!-- 数据组件 -->
            </div>
          </div>
          <div class="goods-footer">
            <div class="goods-article">
              <!-- 商品详情 -->
              <div class="goods-tabs">
<!--                <nav>-->
<!--                  <a>商品详情</a>-->
<!--                </nav>-->
<!--                <div class="goods-detail">-->
<!--                  &lt;!&ndash; 属性 &ndash;&gt;-->
<!--                  <ul class="attrs">-->
<!--                    &lt;!&ndash; <li v-for="item in goodsDetailData" :key="item.value"> &ndash;&gt;-->
<!--                    <span class="dt">{{ goodsDetailData.title }}</span>-->
<!--                    <span class="dd">{{ goodsDetailData.tags }}</span>-->
<!--                    &lt;!&ndash; </li> &ndash;&gt;-->
<!--                  </ul>-->
<!--                  &lt;!&ndash; 图片 &ndash;&gt;-->
<!--                  <img v-for="img in productImages" :key="img" :src="img" />-->
<!--                </div>-->
                <DetailHot :id="$route.params.id" />
              </div>
            </div>
            <!-- 评论 -->
            <div class="goods-aside">
              <div class="review-section">
                <h3 class="review-title">商品评价</h3>
                <div v-if="loadingReviews" class="loading-reviews">
              <el-skeleton :rows="3" animated />
            </div>
            <div v-else-if="!reviews" class="no-reviews">
              <el-empty description="暂无评价" />
            </div>
            <div v-else class="review-list">
              <div v-for="(review,index) in reviews" :key="index" class="review-item">
                <div class="review-header">
                  <el-avatar :src="review.avatarUrl"/>
                  <div class="user-info">
                    <span class="username">{{ review.username || '匿名用户' }}</span>
                    <el-rate
                      v-model="review.rating"
                      disabled
                      show-score
                      text-color="#ff9900"
                      score-template="{value}分"
                    />
                  </div>
                  <span class="review-time">{{ review.createDate }}</span>
                </div>
                <div class="review-content">
                  <p>{{ review.comment }}</p>
                  <div v-if="review.images && review.images.length" class="review-images">
                    <el-image
                      v-for="(img, index) in review.images"
                      :key="index"
                      :src="img"
                      :preview-src-list="review.images"
                      fit="cover"
                      class="review-image"
                    />
                  </div>
                </div>
              </div>
            </div>

              </div>
              <!-- 24小时 -->
              <!-- <DetailHot :hotType="1" :id="goodsDetailData.productId" /> -->
              <!-- 周 -->
              <!-- <DetailHot :hotType="2" /> -->
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.xtx-goods-page {
  .goods-info {
    min-height: 600px;
    background: #fff;
    display: flex;

    .media {
      width: 580px;
      height: 600px;
      padding: 30px 50px;
    }

    .spec {
      flex: 1;
      padding: 30px 30px 30px 0;
    }
  }

  .goods-footer {
    display: flex;
    margin-top: 20px;

    .goods-article {
      width: 840px;
      margin-right: 20px;
    }

    .goods-aside {
      width: 380px;
      min-height: 1000px;
    }
  }

  .goods-tabs {
    min-height: 600px;
    background: #fff;
  }

  .goods-warn {
    min-height: 600px;
    background: #fff;
    margin-top: 20px;
  }

  .number-box {
    display: flex;
    align-items: center;

    .label {
      width: 60px;
      color: #999;
      padding-left: 10px;
    }
  }

  .g-name {
    font-size: 22px;
  }

  .g-desc {
    color: #999;
    margin-top: 10px;
  }

  .g-price {

    font-size: 24px;
    height: 24px;
    line-height: 24px;
    margin: 10px 0;
    color: #ff4f24;

    span {
      font-size: 14px;
      height: 15px;
      line-height: 15px;
      position: relative;
      top: -1px;
    }
  }

  .g-service {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .seller-section {
    display: flex;
    align-items: center;
    gap: 20px;
  }

  .seller-link {
    display: flex;
    align-items: center;
    gap: 12px;
    text-decoration: none;
    color: inherit;
  }

  .seller-info {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .seller-name {
    font-weight: bold;
  }

  .seller-phone {
    font-size: 12px;
    color: #999;
  }

  .report-link {
    margin-left: auto;
  }

  .number-box {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }

  .error-message {
    color: red;
    font-size: 14px;
    margin-top: 10px;
  }

  .success-message {
    color: #1dc779;
    font-size: 14px;
    margin-top: 10px;
  }

  .info-message {
    color: #409eff;
    font-size: 14px;
    margin-top: 10px;
  }

  .btn-group {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
  }

  .btn {
    width: 140px;
  }

  .goods-sales {
    display: flex;
    width: 400px;
    align-items: center;
    text-align: center;
    height: 140px;

    li {
      flex: 1;
      position: relative;

      ~ li::after {
        position: absolute;
        top: 10px;
        left: 0;
        height: 60px;
        border-left: 1px solid #e4e4e4;
        content: "";
      }

      p {
        &:first-child {
          color: #999;
        }

        &:nth-child(2) {
          color: $priceColor;
          margin-top: 10px;
        }

        &:last-child {
          color: #666;
          margin-top: 10px;

          i {
            color: $xtxColor;
            font-size: 14px;
            margin-right: 2px;
          }

          &:hover {
            color: $xtxColor;
            cursor: pointer;
          }
        }
      }
    }
  }
}

.goods-tabs {
  min-height: 600px;
  background: #fff;

  nav {
    height: 70px;
    line-height: 70px;
    display: flex;
    border-bottom: 1px solid #f5f5f5;

    a {
      padding: 0 40px;
      font-size: 18px;
      position: relative;

      > span {
        color: $priceColor;
        font-size: 16px;
        margin-left: 10px;
      }
    }
  }
}

.goods-detail {
  padding: 40px;

  .attrs {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 30px;

    li {
      display: flex;
      margin-bottom: 10px;
      width: 50%;

      .dt {
        width: 100px;
        color: #999;
      }

      .dd {
        flex: 1;
        color: #666;
      }
    }
  }

  > img {
    width: 100%;
  }
}

.btn {
  margin-top: 20px;
}

.bread-container {
  padding: 25px 0;
}

.review-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .review-title {
    font-size: 18px;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f5f5f5;
  }

  .review-item {
    padding: 15px 0;
    border-bottom: 1px solid #f5f5f5;

    &:last-child {
      border-bottom: none;
    }
  }

  .review-header {
    display: flex;
    align-items: center;
    margin-bottom: 10px;

    .user-info {
      flex: 1;
      margin-left: 10px;

      .username {
        font-weight: bold;
        margin-right: 10px;
      }
    }

    .review-time {
      color: #999;
      font-size: 12px;
    }
  }

  .review-content {
    padding-left: 50px;

    p {
      margin: 5px 0;
      line-height: 1.6;
    }
  }

  .review-images {
    margin-top: 10px;

    .review-image {
      width: 80px;
      height: 80px;
      margin-right: 10px;
      border-radius: 4px;
      cursor: pointer;
    }
  }
}

.loading-reviews {
  padding: 20px;
}

.no-reviews {
  padding: 40px 0;
  text-align: center;
  color: #999;
}
</style>
@/stores/car1
